//往dom结构新增标签
let addDom = () => {
    var bg = "<div id='bg' style='background:#800040;width:20px;height:20px;position:absolute;top:0px;left:0px;z-index:1000000;display:none'>&nbsp;</div>";
    $("body").append(bg);
    var stopTask = "<input id='stopTask' type='hidden' value='true'/>";
    $("body").append(stopTask);
    var enter = "<input id='enter' type='hidden' value='true'/>";
    $("body").append(enter);
}
//获取常用语类型
function cateAjax() {
    $.ajax({
        type: "post",
        dataType: "json",
        url: "https://www.lampblog.net/phpextjs/web/Home/Api/categoryList",
        cache: false,
        data: {
            name: "",
        },
        success: function(data) {
            // alert("请求成功");
            var ul = $("#tab");
            for (var i = 0; i < data.length; i++) {
                var txt = data[i];
                var li = document.createElement("li");
                if (i == 0) {
                    li.setAttribute("class", "tab_active")
                }
                li.setAttribute("data_id", txt.id);
                li.innerHTML = txt.name;
                ul.append(li)
            };
            getContent(data[0].id);
        }
    });
};
//切换常用语类型tab
function selectTab() {
    $("#tab").on("click", "li", function() {
        var cateId = $(this).attr("data_id");
        $("#tab>li").removeClass("tab_active");
        $(this).addClass("tab_active");
        $("#tab>li").removeClass("tab_color");
        $(this).addClass("tab_color");
        getContent(cateId)
    })
}
//获取每个分类下的常用回复语
function getContent(id) {
    $.ajax({
        type: "post",
        dataType: "json",
        url: "https://www.lampblog.net/phpextjs/web/Home/Api/quickReplyList",
        cache: false,
        data: {
            "categoryId": id,
        },
        success: function(data) {
            var data = data[0].quickReplyList;
            var str = "";
            var str = '<ul class="main selected">';
            for (i = 0; i < data.length; i++) {
                str += '<li>' + data[i].content + '</li>'
            }
            str += "</ul>"
            $("#myList").html(str);
            //加载成功之后调用li点击事件
            liClick();
        }
    });
}
//弹窗组件
function showLayerWin() {
    var html = "";
    html = '<div id="form">' +
        '<div class="nav">' +
        '<ul id="tab" class="clearfix"></ul>' +
        '</div>' +
        //  '<div class="d-sear">'+
        //  '<input class="searchId" id="searchId" type="text" placeholder="按关键字查询" />'+
        //  '</div>'+
        '<div class="answer clearfix" id="myList">' +
        '</div>' +
        '</div>';
    var w = "380px";
    var h = "370px";
    var offset = 'rt';
    var title = '常用语';
    var content = html;
    layerWin(w, h, offset, title, content, false, 0);
    cateAjax();
    //调用tab的js
    selectTab();
    

    setTimeout(function(){
        newOrderList();
    },2000);

    //执行查询订单数量 支付
    getOrderMassage();
    monitorSet();


}
//物流查询窗口
var arruserArrAll = [];
function showLayerWin2() {
    $("._2wP_Y").each(function(i) {
        if (i == 0) {
            $(this).attr("id", "_2wP_Y");
        }
    })
    var w = "380px";
    var h = "250px";
    var offset = 'rb';
    var title = '批量打招呼';
    var content = "<div><div style='margin:8px 13px'>"+
    "<span  style='font-size:14px;font-weight:none'>手机号</span>"+
    "<div style='position:relative'>"+ //class='selectable-text'
        "<textarea id='phones' type='text' rows='3' cols='50' class='selectable-text' style='margin-top:5px;border-radius:5px;border:1px solid rgba(7, 17, 27, 0.1)'></textarea>"+
        "<a id='clearPhones' style='text-align:center;position:absolute;right:3px;bottom:3px;cursor:pointer'>"+
            "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'>"+
                "<path fill='#C9CCCD' d='M17.25 7.8L16.2 6.75l-4.2 4.2-4.2-4.2L6.75 7.8l4.2 4.2-4.2 4.2 1.05 1.05 4.2-4.2 4.2 4.2 1.05-1.05-4.2-4.2 4.2-4.2z'></path>"+
            "</svg>"+
        "</a>"+
    "</div>"+
    "<span  style='font-size:14px;font-weight:none'>内容</span>"+
    "<div style='position:relative'>"+ //class='selectable-text'
        "<textarea id='calls' type='text' rows='3' cols='50' class='selectable-text' style='margin-top:5px;border-radius:5px;border:1px solid rgba(7, 17, 27, 0.1)'></textarea>"+
        "<a id='clearCalls' style='text-align:center;position:absolute;right:3px;bottom:3px;cursor:pointer'>"+
            "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'>"+
                "<path fill='#C9CCCD' d='M17.25 7.8L16.2 6.75l-4.2 4.2-4.2-4.2L6.75 7.8l4.2 4.2-4.2 4.2 1.05 1.05 4.2-4.2 4.2 4.2 1.05-1.05-4.2-4.2 4.2-4.2z'></path>"+
            "</svg>"+
        "</a>"+
    "</div>"+
    "</div>"+
    "<div style='text-align:center;width:100%;float:left;position:relative'>"+
    "<a id='goOn' style='text-align:center;width:80px;position:absolute;left:13px;cursor:pointer'>继续打招呼</a>"+
    "<div style='width:100%;float:left;'><input type='checkbox' id='checkboxId'/><a id='allCell' style='text-align:center;cursor:pointer'>批量打招呼</a></div>"+
    "<a id='suspend' style='text-align:center;width:80px;position:absolute;right:13px;cursor:pointer'>暂停</a>"+
    "</div>"+
    "</div>";
    layerWin(w, h, offset, title, content, false,0);

    //调用绑定事件
    all_bind_click();
    //调用继续打招呼事件
    goOn_click();

    //暂停打招呼
    suspend_click();

    //清空批量输入语
    var clearCalls = document.getElementById('clearCalls');
    clearCalls.addEventListener('click', function(event) {
        $("#calls").val("");
    });

     //清空批量输入语
     var clearPhones = document.getElementById('clearPhones');
     clearPhones.addEventListener('click', function(event) {
         $("#phones").val("");
     });
    //往dom插入标签
    addDom();

    //获取通讯录的全部好友
    
     document.getElementById("checkboxId").addEventListener("change",function(){
        var _length = $(".rotate-focus-container").length;
        if($('#checkboxId').is(':checked')){
            if(_length>0){
                var ket2 = $(".rotate-focus-container .RLfQR ._2wP_Y ._25Ooe");
                for (var i = 0; i < ket2.length; i++) {
                    var userId = ket2[i].innerText;
                    if(arruserArrAll.indexOf(userId)==-1){
                        arruserArrAll.push(userId);
                    }
                }
            }else{
                document.getElementById("checkboxId").checked = false;
                alert("请点开通讯录再勾选");
            }
        }
     });
}
//公共弹窗组件
function layerWin(w, h, offset, title, content, layerMin,closeBtn) {
    ! function() {
        layer.ready(function() {
            var index = layer.open({
                type: 1,
                title: title,
                maxmin: true,
                area: [w, h],
                offset: offset,
                closeBtn: closeBtn,
                shade: 0, //遮罩 0.3 启动遮罩
                content: content
            });
            if (layerMin == true) {
                layer.min(index);
            }
        });
    }();
}
//公共弹窗组件2
function layerWin2(w, h, offset, title, content, layerMin,closeBtn) {
    ! function() {
        layer.ready(function() {
            var index = layer.open({
                type: 1,
                title: title,
                maxmin: true,
                area: [w, h],
                offset: offset,
                closeBtn: closeBtn,
                anim: 2,
                shade: 0, //遮罩 0.3 启动遮罩
                content: content
            });
            if (layerMin == true) {
                layer.min(index);
            }
        });
    }();
}
//常用语弹窗组件的点击
function liClick() {
    var list = document.getElementById('myList');
    var listChild = list.getElementsByTagName('li');
    var b1, pip1, inhtml, _1UWg0, blockCompose, html;
    for (var i = 0; i < listChild.length; i++) {
        listChild[i].addEventListener('click', function() {
            console.log("123")
            if ($('div').hasClass('_2S1VP')) {
                //获取聊天发送输入框的对象
                b1 = document.getElementsByClassName("_2S1VP")[0];
                pip1 = document.getElementsByClassName("_39LWd")[0];
                pip1.style.visibility = "hidden";
                inhtml = this.innerHTML;
                //b1.innerHTML = inhtml;
                // $("._2S1VP").html(inhtml).focus();
                // hide 设置为2不触发模糊
                $("#hide").val('2');
                $("._2S1VP").html('');
                $("._2S1VP").sendkeys(inhtml);
               
                //bindDom();
                blockCompose = document.getElementsByClassName("block-compose")[0];
                // 鼠标点击发送回复框内容，促发提交聊天历史记录
                setTimeout(function() {
                    PushHistory();
                }, 1000)
            } else {
                alert('请选择聊天窗口才能设置常用语');
            }
        }, false)
    }
}
//调用点击好友列表触发事件
function bindFriendClick() {
    var FriendList = $("._2wP_Y");//$(".chat")
    for (var i = 0; i < FriendList.length; i++) {
        var arrUers = FriendList[i];
        (function(i) {
            //点击好友
            arrUers.addEventListener("click", function() {
                var input = "<input id='hide' type='hidden' value='1'/>";
                if($("#hide").length == 0){
                    $('body').append(input);
                }
                //console.log("bindFriendClick()")
                bindDom();
                //点击好友触发加载红色 黄色数量
                if(!$(this).find("._1AwDx").find('div').is('._15G96')){
                    var f_phone = $(this).find("._25Ooe span").html();
                    if (f_phone.indexOf('+') != -1) {
                        f_phone = f_phone.split("+");
                        f_phone = f_phone[1];
                    }
                    f_phone = f_phone.replace(/[^0-9]+/g, '');
                    if(f_phone !='' && f_phone != null){
                        getOrderMassage2(f_phone);
                    }
                }
            })
        })(i);
    }
}
//创建隐藏域和绑定dom
function set_hide_binDom(){
    var input = "<input id='hide' type='hidden' value='1'/>";
    if($("#hide").length == 0){
        $('body').append(input);
    }
    bindDom();
}
//监控dom输入框变化
var currentSelIndex = -1;
var oldSelIndex = -1;
function bindDom() {
    var searchInput = window.document.getElementsByClassName('_2S1VP')[0];
    var phone = $("#phone").val();
    if (window.addEventListener) {
        //输入框输入调用ajax
        if(searchInput!=null && searchInput !=''){
        searchInput.addEventListener('input', function() {
            //console.log("searchInput.addEventListener");
            var value = $('._2S1VP').html();
            var hide = $("#hide").val();
            if (value != '' && hide == '1') { 
                //搜索历史回复语
                document.onmousedown=function(event){
                    PushHistory();
                }; 
                searchInput.onkeydown=function(event){
                    var e = event || window.event || arguments.callee.caller.arguments[0];   
                     if(e && e.keyCode==32 ){ // 空格键
                        var value2 = $('._2S1VP').html();
                        searchReply(phone, value2);
                     }
                }; 
            } else {
                if (value == '') {
                    //隐藏模糊搜索数据
                    $('.search-content').hide();
                }
            }
        }, false);
        //键盘上下移动
        searchInput.onkeydown = function(event) {
            setTimeout(function(){
                var sc = document.getElementById("search-content"); //获取列表数量
                if (sc) {
                    var liLength = sc.getElementsByTagName("li").length;
                    console.log("event.keyCode"+event.keyCode);
                    if ((event.keyCode == 38 || event.keyCode == 40) && document.getElementById("search-content").style.display != "none") {
                        if (liLength > 0) {
                            oldSelIndex = currentSelIndex;
                            //上移
                            if (event.keyCode == 38) {
                                $("#hide").val('2');
                                if (currentSelIndex == -1) {
                                    currentSelIndex = liLength - 1;
                                } else {
                                    currentSelIndex = currentSelIndex - 1;
                                    if (currentSelIndex < 0) {
                                        currentSelIndex = liLength - 1;
                                    }
                                }
                                if (currentSelIndex != -1) {
                                    document.getElementById("li_" + currentSelIndex).style.color = "red";
                                    var _li = document.getElementById("li_" + currentSelIndex);
                                    _li.click();

                                }
                                if (oldSelIndex != -1) {
                                    document.getElementById("li_" + oldSelIndex).style.color = "#454545";
                                }
                            }
                            //下移
                            if (event.keyCode == 40) {
                                $("#hide").val('2');
                                if (currentSelIndex == liLength - 1) {
                                    currentSelIndex = 0;
                                } else {
                                    currentSelIndex = currentSelIndex + 1;
                                    if (currentSelIndex > liLength - 1) {
                                        currentSelIndex = 0;
                                    }
                                }
                                if (currentSelIndex != -1) {
                                    document.getElementById("li_" + currentSelIndex).style.color = "red";
                                    var _li = document.getElementById("li_" + currentSelIndex);
                                    _li.click();
                                }
                                if (oldSelIndex != -1) {
                                    document.getElementById("li_" + oldSelIndex).style.color = "#454545";
                                }
                            }
                        }
                    }
                }
                if (event.keyCode != 38 && event.keyCode != 40) {
                    $("#hide").val('1');
                }
                if (event.keyCode == 13) {
                    //隐藏模糊搜索数据
                    $('.search-content').hide();
                }
            },2000);
            
        }
    }
  }
    var friend_phone = $("#friend_phone").val();
    setTimeout(function(){
        //console.log("GetKeyDown2(friend_phone,'2')");
        GetKeyDown2(friend_phone,'2');
    },2000);
}
//搜索历史回复语
function searchReply(phone, value) {
    $.ajax({
        type: "post",
        dataType: "json",
        url: "https://www.lampblog.net/phpextjs/web/Home/ApiSearch/searchReply",
        cache: false,
        data: {
            "phone": phone,
            "msg": value
        },
        success: function(data) {
            var status = data.status;
            var list = data.list;
            var html = "";
            if (status) {
                html = '<div class="search-content" id="search-content"><ul>';
                for (i = 0; i < list.length; i++) {
                    html += '<li id="li_' + i + '">' +
                        '<div class="_1VfKB"><span data-icon="status-dblcheck-ack" class=""><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path fill="#4FC3F7" d="M17.394 5.035l-.57-.444a.434.434 0 0 0-.609.076l-6.39 8.198a.38.38 0 0 1-.577.039l-.427-.388a.381.381 0 0 0-.578.038l-.451.576a.497.497 0 0 0 .043.645l1.575 1.51a.38.38 0 0 0 .577-.039l7.483-9.602a.436.436 0 0 0-.076-.609zm-4.892 0l-.57-.444a.434.434 0 0 0-.609.076l-6.39 8.198a.38.38 0 0 1-.577.039l-2.614-2.556a.435.435 0 0 0-.614.007l-.505.516a.435.435 0 0 0 .007.614l3.887 3.8a.38.38 0 0 0 .577-.039l7.483-9.602a.435.435 0 0 0-.075-.609z"></path></svg></span></div>' +
                        '<span class="inlineblock">' + list[i].content + '</span>' +
                        '</li>';
                }
                html += "</ul></div>";
                if (!$('div').hasClass('search-content')) {
                    $('._2jVLL').append(html);
                } else {
                    $('.search-content').replaceWith(html);
                }
                var inputContainer = $('._2jVLL')
                $(document).on('click', function(e) {
                    $('.search-content').hide();
                });
                $('.search-content').on('click', function(e) {
                    e.stopPropagation();
                });
                initClick();
            }
        }
    });
}
//初始化点击事件
function initClick() {
    var list = document.getElementById('search-content');
    var listChild = list.getElementsByTagName('li');
    var b1, pip1, inhtml, _1UWg0, blockCompose, html;
    for (var i = 0; i < listChild.length; i++) {
        listChild[i].addEventListener('click', function(event) {
            if ($('div').hasClass('_2S1VP')) {
                //获取聊天发送输入框的对象
                b1 = document.getElementsByClassName("_2S1VP")[0];
                pip1 = document.getElementsByClassName("_39LWd")[0];
                pip1.style.visibility = "hidden";
                inhtml = $(this).find(".inlineblock").html();
                $("._2S1VP").html('');
                //$('._2S1VP').attr('id', '_2S1VP');
                var searchInput = window.document.getElementsByClassName('_2S1VP')[0];
                $("._2S1VP").sendkeys(inhtml);
            }
        }, false);
        $("#hide").val('1');
    }
}
//批量打招呼
function all_bind_click() {
    var allCell = document.getElementById('allCell');
    allCell.addEventListener('click', function(event) {
        //获取好友列表数组
        var arruserArr = [];
        var phones = $("#phones").val();
        //判断是否有填手机号，没有的话从好友列表获取
        if(phones!="" && phones!=null){
            var phoneArray = phones.split(",");
            $.each(phoneArray, function(i, n) {
                arruserArr.push(n);
            });
        }else{
            var checkboxId = $('#checkboxId').is(':checked');
            if(arruserArrAll.length > 0 && checkboxId == true){
                arruserArr = arruserArrAll;
            }else{
                var ket = $("._25Ooe");
            for (var i = 0; i < ket.length; i++) {
                var userId = ket[i].innerText;
                if(arruserArr.indexOf(userId)==-1){
                    arruserArr.push(userId);
                }
            }
            }
        }
        //console.log(arruserArr);
        var calls = $("#calls").val();
        if(calls!="" && calls!=null){
             //任务跑起
            $("#stopTask").val('true');
            $("#enter").val('false');
            taskGo(arruserArr);
        }else{
            alert("请输入批量打招呼的内容");
        }
    }, false);
}
var newArr = new Array();
//好友列表任务启动,开始打招呼
function taskGo(arruserArr){
    //复制新的数组
    newArr = arruserArr.slice();
    //获取批量打招呼语
    var calls = $("#calls").val();
     //创建任务控制类
     var TaskControl = function(taskFunction, finishFunction){
        this.finish = false;
        this.next = function(){
            if(!this.finish ){
                    taskFunction.call(this);
            }else{
                finishFunction.call(this);
            }
        };
    };
    //任务
    var task = function(){
        //deal不知道你怎么定义的，估计是异步的，这里用setTimeout实现
        var deal = function(){
            var stopTask = $("#stopTask").val();
            var U0cj3 = $(".U0cj3").length;
            var U0cj3Html = $(".U0cj3").html();
            var res = false;
            if(U0cj3 == 0){
                if(U0cj3Html != '手机未连接'){
                    res = true;
                }
            }
            //true任务执行  false停止执行
            if(stopTask == 'true'){
                if( res == true ){
                    //异步执行了
                    this.index++;
                    console.time("任务：" + this.index);
                    //判断列表中还有没有任务
                    // console.log(this.index);
                    // console.log(this.data.length);
                    if( this.index >= this.data.length ){
                        //设置 finish 为 true
                        this.finish = true;
                    }else{
                        //如果还有任务，开始处理任务
                        var runLog = {
                            "时间" : new Date(),
                            "索引" : this.index,
                            "值" : this.data[this.index]
                        };
                        if(stopTask == 'true'){
                            $("#input-chatlist-search").sendkeys(this.data[this.index]);
                            $("#input-chatlist-search").val('');
                            $("#input-chatlist-search").sendkeys(this.data[this.index]);
                            var delUser = this.data[this.index];
                            setTimeout(function(){
                                if(stopTask == 'true'){
                                    var _3xG0U = $("._3xG0U").length;
                                    if(_3xG0U == 0){
                                        $("#bg").css('display','block');
                                        setTimeout(function(){
                                            if($("._2S1VP")){
                                                $("._2S1VP").html('');

                                                $("._2S1VP").sendkeys(calls);
                                                sendInfo();
                                                setFriend_phone();
                                                
                                            }
                                        },2000);
                                    }else{
                                        alert("没有找到对话 联系人或信息");
                                        return;
                                    }
                                }else{
                                    return;
                                }
                            },2000);
                            console.log(runLog);    //每次执行日志
                            this.cache.push(runLog);
                            removeByValue(newArr,this.data[this.index]);
                        }else{
                            return;
                        }
                    }
                    console.timeEnd("任务：" + this.index);
                    this.next();
                    //继续下一个
            }else{
                alert("手机未连接,请确定手机有良好的网络讯号。");
                    return;
            }
          }else{
              return;
          }
        }.bind(this); 
        //setTimeout 是为了模仿异步的效果，随时 时间完成
        var timeD = "";
        if(this.index == -1){
            timeD = parseInt(2000);
        }else{
            timeD = parseInt(7000);
        }
        setTimeout(deal,timeD);
        //setTimeout(deal, parseInt(Math.random() * 1000));
    };
    var finish = function(){
        $("#bg").hide();
        $("#enter").val('true');
        set_hide_binDom();
        console.log("任务完成");
        console.table(this.cache);
        alert("批量发送完成");
         // 历史记录功能模块
        // 调用获取好友列表方法
        // GETFriends();
        // ChangeFriend();
        getOrderMassage();
        var friend_phone = $("#friend_phone").html();
        GetKeyDown(friend_phone);
        return;
    };
    var run = new TaskControl(task, finish);
    //为了测试方便，将数据也绑定过来
    run.data = arruserArr; //列表
    run.index = -1;    //默认索引
    run.cache = []; //设置个执行缓存
    run.next();    //开始执行
}
//批量打招呼
function goOn_click(){
    var goOn = document.getElementById('goOn');
    goOn.addEventListener('click', function(event) {
        //任务再次跑起
        $("#stopTask").val('true');
        $("#enter").val('false');
        if(newArr.length > 0 ){
            taskGo(newArr);
        }else{
            alert("没有需要继续打招呼的好友,可能已经全部跑完");
        }
    }, false);
}
//暂停打招呼
function suspend_click(){
    var suspend = document.getElementById('suspend');
    suspend.addEventListener('click', function(event) {
        stopTask();
    }, false);
}
//删除数组已执行的元素
function removeByValue(arr, val) {
  for(var i=0; i<arr.length; i++) {
    if(arr[i] == val) {
      arr.splice(i, 1);
      break;
    }
  }
}
//发送信息
function sendInfo(){
    var stopTask = $("#stopTask").val();
    setTimeout(function(){
        if(stopTask == 'true' && document.getElementsByClassName("_2lkdt")[0]){
            document.getElementsByClassName("_2lkdt")[0].click();
        }else{
            return;
        }
    },2000);
}
function sleep(n){
    var start=new Date().getTime();//定义起始时间的毫秒数
    while(true){
     var time=new Date().getTime();//每次执行循环取得一次当前时间的毫秒数
     if(time-start>n){//如果当前时间的毫秒数减去起始时间的毫秒数大于给定的毫秒数，即结束循环
      break;
     }
    }
}
//设置好友手机
function setFriend_phone(){
    var friend_phone = $("._3AwwN ._2zCDG ._1wjpf").html();
    if (friend_phone.indexOf('+') != -1) {
        friend_phone = friend_phone.split("+");
        friend_phone = friend_phone[1];
    }
    friend_phone = friend_phone.replace(/[^0-9]+/g, '');
    var p_html = "<input id='friend_phone'class='friend_phone'  type='hidden' value='"+friend_phone+"'/>";
    if (!$('#friend_phone').hasClass('friend_phone')) {
        $("body").append(p_html);
    } else {
        if(friend_phone!=null && friend_phone!=''){
            $("#friend_phone").val(friend_phone);
        }else{
            $("#friend_phone").val('');
        }
        
    }
    return friend_phone;
}
//停止任务执行动作
function stopTask(){
    $("#bg").hide();
    $("#stopTask").val('false');
    $("#enter").val('true');
    set_hide_binDom();
    alert("已停止打招呼");
     // 历史记录功能模块
     // 调用获取好友列表方法
     // GETFriends();
     // ChangeFriend();
      getOrderMassage();
    var friend_phone = $("#friend_phone").html();
    GetKeyDown(friend_phone);
}

//监听搜索好友列表添加订单数量 日期 未支付单
function monitorSet(){
    var chatlist = window.document.getElementById('input-chatlist-search');
    if (window.addEventListener) {
        chatlist.addEventListener('input', function() {
            var enter = $("#enter").val();
            if(enter == 'true'){
                if($("._3WZoe").length == 0){
                    setTimeout(function(){
                        getOrderMassage();
                    },1000);
                }
            }
        });
        chatlist.onkeydown=function(event){
            var e = event || window.event || arguments.callee.caller.arguments[0];   
             if(e && e.keyCode==13 ){ // 回车
                var enter = $("#enter").val();
                if(enter == 'true'){
                    setTimeout(function(){
                        set_hide_binDom();
                        var friend_phone = setFriend_phone();
                        GetKeyDown(friend_phone);
                        getOrderMassage();
                    },1000);
                    
                }
                
             }
        }; 
    }
}
var orderArr=[];
var orderArrNew=[];
//新订单列表
function newOrderList(){
    var  phone = $("#phone").val();
    $.ajax({
        type: "post",
        dataType: "json",
        url: "https://www.lampblog.net/phpextjs/web/Home/Api/newOrderList",
        cache: false,
        data: {
            "token":"7a3bd68cfe8432b738bedf2aedc4e5f5",
            "account": phone
        },
        success: function(data) {
            if(data!="" && data!=null){
                var data = data[0].data;
                var str="";
                var orders_number="";
                for(var i=0;i<data.length;i++){
                    str+="<tr>"+
                        "<td class='selectable-text' style='border:1px solid #000;text-align: center;padding:4px 4px;width:80px;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)'>"+data[i].orders_number+"</td>"+
                        "<td class='selectable-text' style='border:1px solid #000;text-align: center;padding:4px 4px;width:70px;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)'>"+data[i].order_total_paid+"</td>"+
                        "<td class='selectable-text' style='border:1px solid #000;text-align: center;padding:4px 4px;width:90px;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)'>"+data[i].shipping_mobile+"</td>"+
                        "<td class='selectable-text' style='border:1px solid #000;text-align: center;padding:4px 4px;width:100;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)'>"+data[i].orders_status+"</td>"+
                        "<td class='selectable-text' style='border:1px solid #000;text-align: center;padding:4px 4px;width:100;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)'>"+data[i].date_purchased+"</td>"+
                    "</tr>";
                    orders_number += data[i].orders_number;
                }
                
                var table = '<table id="orderTable" style="width:95%;margin:10px;" class="selectable-text;font-size:13.5px;color:rgb(68, 68, 68)">'+
                        '<tr>' +
                            '<th class="selectable-text" style="border:1px solid #000;text-align: center;padding:4px 4px;width:80px;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)">订单编号</th>' +
                            '<th class="selectable-text" style="border:1px solid #000;text-align: center;padding:4px 4px;width:70px;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)">金额</th>' +
                            '<th class="selectable-text" style="border:1px solid #000;text-align: center;padding:4px 4px;width:90;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)">手机号码</th>'+
                            '<th class="selectable-text" style="border:1px solid #000;text-align: center;padding:4px 4px;width:100;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)">状态</th>'+
                            '<th class="selectable-text" style="border:1px solid #000;text-align: center;padding:4px 4px;width:100;vertical-align: middle;font-size:13.5px;color:rgb(68, 68, 68)">时间</th>'+
                        '</tr>'+
                        str+
                    '</table>'
                var w = "440px";
                var h = "300px";
                var offset = 'rb';
                var title = '24小时订单提醒';
                var content = table;
                if(orderArr.length == 0){
                    layerWin2(w, h, offset, title, content, false, '1');
                    orderArr.push(orders_number);
                }else{
                    orderArrNew.push(orders_number);
                    if(orderArr.sort().toString() != orderArrNew.sort().toString()){
                        layerWin2(w, h, offset, title, content, false, '1');
                        orderArr.splice(0,orderArrNew.length);
                        orderArr.push(orders_number);
                    }
                }
                
                orderArrNew.splice(0,orderArrNew.length);
               
            }
            
        }
    });
}
//判断订单提醒窗口是否被关闭了
function showOrderList(){
    if ($("#orderTable").length === 0) {
        newOrderList();
   }else{
       return false;
   }
}
//获取订单消息
function getOrderMassage(){
    var phones="";
    var ket = $("._25Ooe"); //var ket = $(".chat-title");
    for (var i = 0; i < ket.length; i++) {
        if(i<10){
            var userId = ket[i].innerText;
            if (userId.indexOf('+') != -1) {
                userId = userId.split("+");
                userId = userId[1];
            }
            userId = userId.replace(/[^0-9]+/g, '');
            if(userId!=null && userId!=''){
                phones+=userId+","
            }
        }
    }
    phones = phones.substring(0,phones.length-1);
    $.ajax({
        type: "post",
        dataType: "json",
        url: "https://www.lampblog.net/phpextjs/web/Home/Api/getOrderMassage",
        cache: false,
        data: {
            "token":"7a3bd68cfe8432b738bedf2aedc4e5f5",
            "account_phone": phones
        },
        success: function(data) {
                for(var i=0; i<data.length;i++){
                    var account_phone = data[i].account_phone
                    var count_week = data[i].countInfo.count_week;
                    var count_year = data[i].countInfo.count_year;
                    var month_day = data[i].countInfo.month_day;
                    //最新订单时间(年月）
                    var dataTime ='<div class="isTime" style="text-align:right;font-size:13px;margin-top:5px;color:rgba(0,0,0,0.6)" title="最新订单时间">'+month_day+'</div>';
                    //用户栏显示最近一周未支付订单（红色）
                    var week = '<div class="_15G96" style="transform: scaleX(1) scaleY(1); opacity: 1;margin-left:4px;margin-right:2px"><span class="OUeyt" style="background-color:#EA4335" title="最近一周未支付订单">'+count_week+'</span></div>'
                    //最近三个月客户的订单(已付+未付)（黄色）
                    var year = '<div class="_15G96" style="transform: scaleX(1) scaleY(1); opacity: 1;"><span class="OUeyt" style="background-color:#FBC013" title="最近三个月客户的订单(已付+未付)">'+count_year+'</span></div>'
                    setOrderTime(account_phone,dataTime,week,year,count_week,count_year);
                }
        }
    });

    GETFriends();
    ChangeFriend();
    //好友列表绑定点击事件
    bindFriendClick();
}
//设置订单时间
function setOrderTime(account_phone,dataTime,week,year,count_week,count_year){
    var chatBody = $("._2wP_Y ._3j7s9");//$("._2wP_Y .chat-body")
    for(var i=0;i<chatBody.length;i++){
        if(i < 10){
            var userId =  chatBody.find('._25Ooe').find('span').eq(i).html();
            if (userId.indexOf('+') != -1) {
                userId = userId.split("+");
                userId = userId[1];
            }
            userId = userId.replace(/[^0-9]+/g, '');
            if(userId == account_phone){
                if(!$("._3j7s9 ._1AwDx").eq(i).find('div').is('._15G96')){
                    if(count_week != 0 ){
                        $("._3j7s9 ._1AwDx").eq(i).append(week);
                    }
                    if(count_year != 0 ){
                        $("._3j7s9 ._1AwDx").eq(i).append(year);
                    }
                }
                if(!$("._3j7s9").eq(i).find('div').is('.isTime')){
                    chatBody.eq(i).append(dataTime);
                }
            }
        }
    }
}
//获取订单消息2
function getOrderMassage2(friend_phone){
    $.ajax({
        type: "post",
        dataType: "json",
        url: "https://www.lampblog.net/phpextjs/web/Home/Api/getOrderMassage",
        cache: false,
        data: {
            "token":"7a3bd68cfe8432b738bedf2aedc4e5f5",
            "account_phone": friend_phone
        },
        success: function(data) {
                for(var i=0; i<data.length;i++){
                    var account_phone = data[i].account_phone
                    var count_week = data[i].countInfo.count_week;
                    var count_year = data[i].countInfo.count_year;
                    var month_day = data[i].countInfo.month_day;
                    //最新订单时间(年月）
                    var dataTime ='<div class="isTime" style="text-align:right;font-size:13px;margin-top:5px;color:rgba(0,0,0,0.6)" title="最新订单时间">'+month_day+'</div>';
                    //用户栏显示最近一周未支付订单（红色）
                    var week = '<div class="_15G96" style="transform: scaleX(1) scaleY(1); opacity: 1;margin-left:4px;margin-right:2px"><span class="OUeyt" style="background-color:#EA4335" title="最近一周未支付订单">'+count_week+'</span></div>'
                    //最近一年客户的订单(已付+未付)（黄色）
                    var year = '<div class="_15G96" style="transform: scaleX(1) scaleY(1); opacity: 1;"><span class="OUeyt" style="background-color:#FBC013" title="最近三个月客户的订单(已付+未付)">'+count_year+'</span></div>'
                    setOrderTime2(account_phone,dataTime,week,year,count_week,count_year);
                   
                }
                
        }
    });
}
//设置订单时间2
function setOrderTime2(account_phone,dataTime,week,year,count_week,count_year){
    var chatBody = $("._2wP_Y ._3j7s9");
    for(var i=0;i<chatBody.length;i++){
            var userId =  chatBody.find('._25Ooe').find('span').eq(i).html();
            if (userId.indexOf('+') != -1) {
                userId = userId.split("+");
                userId = userId[1];
            }
            userId = userId.replace(/[^0-9]+/g, '');
            if(userId == account_phone){
                if(!$("._3j7s9 ._1AwDx").eq(i).find('div').is('._15G96')){
                    if(count_week != 0 ){
                        $("._3j7s9 ._1AwDx").eq(i).append(week);
                    }
                    if(count_year != 0 ){
                        $("._3j7s9 ._1AwDx").eq(i).append(year);
                    }
                }
                
                if(!$("._3j7s9").eq(i).find('div').is('.isTime')){
                    chatBody.eq(i).append(dataTime);
                }
            }
    }
}

$(function(){
    //当键盘按下的时候取消bg回车事件
    document.onkeydown=function(){
        if (window.event && window.event.keyCode == 13) { 
            
            var enter = $("#enter").val();
            if(enter == 'true'){
                //var friend_phone = setFriend_phone();
                //GetKeyDown2(friend_phone,'1');
            }
            //set_hide_binDom();
            $("#bg").css("display","none");
            var enter = $("#enter").val();
            if(enter == 'false'){
                return false;
            }else{
                return true;
            }
        }
         if(window.event && window.event.keyCode == 9){ // Tab 键
            //stopTask();
         }
    }; 
})
//定时执行，检查元素存在就停止执行
function autoPlay(){
    　　time = setInterval(function(){
            if($(".app-wrapper-main").length!=0){
                clearInterval(time),function(){
                    　autoPlay();
                }　　
                // 插入订单查询弹出按钮
                beforSertTabBtn();
                //调用layer弹窗组件
                showLayerWin();
                showLayerWin2();
                // labPage();
                //好友列表绑定点击事件
                //bindFriendClick();
                //获取当前登录人手机号
                var phone = "";
                if ("undefined" != typeof localStorage.waMyNum && "" !== localStorage.waMyNum) {
                    phone = localStorage.waMyNum;
                    var str = phone.substring(2); //从第二个字符开始截取
                    var arr = str.split("@");
                    var input_phone = "<input id='phone' type='hidden' value='" + arr[0] + "'/>";
                    $("body").append(input_phone);
                }
                // 历史记录功能模块
                // // 调用获取好友列表方法
                GETFriends();
                ChangeFriend();
            }
    　　},500);
    
    }
window.onload=function(){
    //监听某个元素是否存在，自动执行
    autoPlay();
    
    //假设这里每个五分钟执行一次taskBegin函数
   taskBegin();
}
//5分钟调用一次查查订单的接口
function taskBegin(){
    setInterval(showOrderList,1000*60*5);//这里的1000表示1秒有1000毫秒,1分钟有60秒,5表示总共5分钟
}